﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using My.SharePoint.STSADM.Commands.OperationHelpers;
using IdeasFree.SharePoint.StsAdm.SPJobs;
using IdeasFree.SharePoint.StsAdm.Logger;

namespace IdeasFree.SharePoint.StsAdm.Commands.Helpers
{
    /// <summary>
    /// Operation helper.
    /// </summary>
    internal partial class Operation
    {
        /// <summary>
        /// Register DeployResourceJobDefinition to one of active Web Application in farm.
        /// </summary>
        /// <param name="Params"></param>
        /// <param name="keyValues"></param>
        internal static void DeployFarmBinContent(SPParamCollection Params, System.Collections.Specialized.StringDictionary keyValues)
        {

            SPWebServiceCollection webServices = new SPWebServiceCollection(SPFarm.Local);
            var spWebApp = (from ws in webServices
                            where ws.WebApplications.Where( wsApp =>
                                                            wsApp.IsAdministrationWebApplication == false &&
                                                            wsApp.Status == SPObjectStatus.Online
                                                          ).Count() > 0
                            select ws.WebApplications.FirstOrDefault<SPWebApplication>()).First();

            if (spWebApp != null)
            {
                // Check if job already registered. 
                var job = spWebApp.JobDefinitions.GetValue<DeployResourceJobDefinition>(Constants.DEPLOYFARMCONTENTBINJOB);
                if (job != null)
                {
                    job.Execute(job.Service.Id);
                }
                else
                {
                    SPOneTimeSchedule deployBinContentSchedule = new SPOneTimeSchedule(DateTime.Now.AddMinutes(1));
                    DeployResourceJobDefinition deployBinContentJob =
                        new DeployResourceJobDefinition(Constants.DEPLOYFARMCONTENTBINJOB, new EventLogger(),spWebApp, SPJobLockType.None);
                    deployBinContentJob.Schedule = deployBinContentSchedule;                    
                    deployBinContentJob.Update();
                }
            }
        }
    }
}
